package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.StoreCommodityMapper;
import com.example.crossborderecommerce.service.*;
import com.example.crossborderecommerce.service.IStoreCommodityService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 仓库货物模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/store-commodity")
public class StoreCommodityController {
    @Resource
    IStoreCommodityService storeCommodityService;
    @Resource
    IStoreService storeService;
    @Resource
    IProductService productService;
    @Resource
    StoreCommodityMapper storeCommodityMapper;

    /**
     * 添加仓库货物
     * @param storeCommodity
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody StoreCommodity storeCommodity) {
        if (storeCommodity.getQuantity()>=storeCommodity.getMinimumQuantity()){
            storeCommodity.setStatus("正常");
        }
        else {
            storeCommodity.setStatus("异常");
        }
        boolean res = storeCommodityService.save(storeCommodity);
        if(res) {
            return Result.success("添加仓库货物成功！");
        }
        return Result.error("添加仓库货物失败！");
    }

    /**
     * 删除仓库货物
     * @param storeCommodity
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody StoreCommodity storeCommodity) {
        boolean res = storeCommodityService.removeById(storeCommodity);
        if(res) {
            return Result.success("删除仓库货物成功！");
        }
        return Result.error("删除仓库货物失败！");
    }


    /**
     * 查询所有仓库货物
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<StoreCommodity> storeCommodityList = storeCommodityService.list();
        if(storeCommodityList == null) {
            return Result.error("获取全部仓库货物失败！");
        }
        for(StoreCommodity storeCommodity : storeCommodityList) {
            if(storeCommodity.getStoreId() != null) {
                Store store = storeService.getById(storeCommodity.getStoreId());
                storeCommodity.setStoreName(store.getName());
            }
            if (storeCommodity.getProductId() !=null){
                Product product = productService.getById(storeCommodity.getProductId());
                storeCommodity.setProductName(product.getName());
            }
        }
        return Result.success("获取全部仓库货物成功！", storeCommodityList);
    }

    /**
     * 删除一系列仓库货物
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> storeCommodityIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = storeCommodityService.removeByIds(storeCommodityIds);
        if(res) {
            return Result.success("删除仓库货物成功");
        }
        return Result.error("删除店铺货物失败！");
    }

    /**
     * 修改仓库货物
     * @param storeCommodity
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody StoreCommodity storeCommodity) {
        if (storeCommodity.getQuantity()>=storeCommodity.getMinimumQuantity()){
            storeCommodity.setStatus("正常");
        }
        else {
            storeCommodity.setStatus("异常");
        }
        boolean res = storeCommodityService.saveOrUpdate(storeCommodity);
        if (res) {
            return Result.success("修改仓库货物成功！");
        }
        return Result.error("修改仓库货物失败！");
    }

    /**
     * 查询货物对应的仓库
     * @return
     */
    @GetMapping("/findStoreByCommodityId")
    public Result findStoreByCommodityId(@RequestParam(defaultValue = "-1") String storeCommodityId) {
        Store store = storeCommodityService.findStoreByCommodityId(storeCommodityId);
        if(store == null) {
            return Result.error("获取仓库信息失败！");
        }
        return Result.success(store);
    }

    /**
     * 查询id对应的仓库
     * @return
     */
    @GetMapping("/findStoreCommodityById")
    public Result findStoreCommodityById(@RequestParam String storeCommodityId) {
        StoreCommodity storeCommodity = storeCommodityService.getById(storeCommodityId);
        if(storeCommodity == null) {
            return Result.error("获取库存信息失败！");
        }
        return Result.success(storeCommodity);
    }

    @GetMapping("/findStoreCommodityByProductAndStoreId")
    public Result findStoreCommodityByProductAndStoreId(@RequestParam String productId,@RequestParam String storeId) {
        StoreCommodity storeCommodity = storeCommodityMapper.findByStoreIdProductId(storeId,productId);
        return Result.success(storeCommodity);
    }

    /**
     * 分页查询所有仓库货物
     * @param productName
     * @param storeId
     * @param status
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "") String productName,
                           @RequestParam(defaultValue = "-1") String storeId,
                           @RequestParam(defaultValue = "全部") String status,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        Page<StoreCommodity> storeCommodityPage = new Page<>(pageNum, pageSize);
        List<StoreCommodity> storeCommodityList = storeCommodityMapper.getStoreCommodityByPage(storeCommodityPage, productName, storeId, status);
        for(StoreCommodity storeCommodity : storeCommodityList) {
            Product product = productService.getById(storeCommodity.getProductId());
            storeCommodity.setProductName(product.getName());
            Store store = storeService.getById(storeCommodity.getStoreId());
            storeCommodity.setStoreName(store.getName());
        }
        Page<StoreCommodity> newStoreCommodityPage = new Page<>(pageNum, pageSize);
        newStoreCommodityPage.setRecords(storeCommodityList);
        newStoreCommodityPage.setTotal(storeCommodityPage.getTotal());
        return Result.success("成功查询所有仓库货物！",newStoreCommodityPage);
    }
    /**
     * 导出仓库货物明细
     * @param productName
     * @param storeId
     * @param status
     * @param response
     * @return
     */
    @GetMapping("exportStoreCommmodityList")
    public Result exportStoreCommodityList(@RequestParam(defaultValue = "") String productName,
                                         @RequestParam(defaultValue = "-1") String storeId,
                                         @RequestParam(defaultValue = "全部") String status,
                                         HttpServletResponse response) {
        QueryWrapper<StoreCommodity> queryWrapper = new QueryWrapper<>();
        List<StoreCommodity> storeCommodityList = storeCommodityService.list(queryWrapper);
        for(StoreCommodity storeCommodity : storeCommodityList) {
            Product product = productService.getById(storeCommodity.getProductId());
            storeCommodity.setProductName(product.getName());
            Store store = storeService.getById(storeCommodity.getStoreId());
            storeCommodity.setStoreName(store.getName());
        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("货物名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("仓库名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("可用量");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("期望可用量");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("预警状态");
        cell.setCellStyle(style);
        for (int i = 0; i < storeCommodityList.size(); i++) {
            row = sheet.createRow(i + 1);
            StoreCommodity storeCommodity =storeCommodityList.get(i);
            row.createCell((short) 0).setCellValue(storeCommodity.getId());
            row.createCell((short) 1).setCellValue(storeCommodity.getProductName());
            row.createCell((short) 2).setCellValue(storeCommodity.getStoreName());
            row.createCell((short) 3).setCellValue(storeCommodity.getQuantity());
            row.createCell((short) 4).setCellValue(storeCommodity.getMinimumQuantity());
            row.createCell((short) 5).setCellValue(storeCommodity.getStatus());
        }
        String fileName = "exportStoreCommodityList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportStoreCommodityList");
    }
    /**
     * 查询产品对应的多个仓库
     * @return
     */
    @GetMapping("/findStoreByStoreCommodityIds")
    public Result findStoresByStoreCommodityIds(@RequestParam(defaultValue = "-1") String storeCommodityId) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        StoreCommodity storeCommodity =storeCommodityService.getById(storeCommodityId);
        queryWrapper.eq("id",storeCommodity.getStoreId());
        List<Store> storeList=storeService.list(queryWrapper);
        return Result.success(storeList);
    }
    /**
     * 获取所有仓库货物种类数
     * @return
     */
    @GetMapping("/findAllCommoditiy")
    public int findAllCommoditiy() {
        List<StoreCommodity> storeCommodityList = storeCommodityService.list();
        if(storeCommodityList == null) {
            return 0;
        }
        return storeCommodityList.size();
    }
    /**
     * 获取所有仓库货物数量
     * @return
     */
    @GetMapping("/findAllCommodities")
    public int findAllCommodities() {
        List<StoreCommodity> storeCommodityList = storeCommodityService.list();
        if(storeCommodityList == null) {
            return 0;
        }
        int sum=0;
        for(StoreCommodity storeCommodity : storeCommodityList) {
           sum=sum+storeCommodity.getQuantity();
        }
        return sum;
    }

    /**
     * 根据仓库类型查询仓库货物量
     * @param type
     * @return
     */
    @GetMapping("/findStoreCommodityByType")
    public Result findStoreCommodityByType(@RequestParam("type") String type) {
        return Result.success(storeCommodityMapper.findStoreCommodityByType(type));
    }

    /**
     * 根据仓库类型查询货物类别总数
     * @param type
     * @return
     */
    @GetMapping("/findCategoryCountByType")
    public Result findCategoryCountByType(@RequestParam("type") String type) {
        return Result.success(storeCommodityMapper.findCategoryCountByType(type));
    }

    /**
     * 根据仓库类型查询仓库期望库存量
     * @param type
     * @return
     */
    @GetMapping("/findStoreMinimumCommodityByType")
    public Result findStoreMinimumCommodityByType(@RequestParam("type") String type) {
        return Result.success(storeCommodityMapper.findStoreCommodityByType(type));
    }

    /**
     * 根据货物状态获得货物个数(注：不是货物总数量，而是有多少个货物)
     * @param status
     * @return
     */
    @GetMapping("/findStoreCommodityCountByStatus")
    public Result findStoreCommodityCountByStatus(@RequestParam("status") String status) {
        return Result.success(storeCommodityMapper.findStoreCommodityCountByStatus(status));
    }

    /**
     * 根据仓库类型获取正常的货物个数
     * @return
     */
    @GetMapping("/findNormalCountByType")
    public Result findNormalCountByType(@RequestParam String type) {
        return Result.success(storeCommodityMapper.findNormalCountByType(type));
    }

    /**
     * 根据仓库类型获取缺货的货物个数
     * @return
     */
    @GetMapping("/findLackCountByType")
    public Result findLackCountByType(@RequestParam String type) {
        return Result.success(storeCommodityMapper.findLackCountByType(type));
    }

    /**
     * 根据仓库类型获取断货的货物个数
     * @return
     */
    @GetMapping("/findEmptyCountByType")
    public Result findEmptyCountByType(@RequestParam String type) {
        return Result.success(storeCommodityMapper.findEmptyCountByType(type));
    }
}
